package com.lepu.app.fun.chat.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.utils.CharacterParser;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.fun.chat.adapter.MembersSortAdapter;
import com.lepu.app.fun.chat.bean.BeanLectureChatUser;
import com.lepu.app.fun.chat.util.ClearEditText;
import com.lepu.app.fun.chat.util.LectureUtil;
import com.lepu.app.fun.chat.util.PinyinComparatorUtil;
import com.lepu.app.fun.chat.util.SideBarUtil;
import com.lepu.app.fun.my.bean.BeanMyActivityDetail;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GroupMembersActivity extends BaseFragmentActivity implements
        OnTopbarNewLeftLayoutListener, AsyncRequest {

    private static final int MSG_DATA_SUCCESS = 10;
    private static final int MSG_DATA_FAIL = 11;

    private SideBarUtil mSideBarUtil;
    private TextView mCenterTip;

    private ArrayList<BeanLectureChatUser> mDataArrayList;
    private ListView mDataListView;
    private MembersSortAdapter mAdapter;

    private String mGroupID = "";

    private CharacterParser mCharacterParser;
    private PinyinComparatorUtil mPinyinComparatorUtil;

    LinearLayout mAllDataLayout;
    LinearLayout mSearchDataLayout;
    EditText mContentEditText;

    ListView mSearchDataListView;
    MembersSortAdapter mFilterAdapter;
    ArrayList<BeanLectureChatUser> mSearchDataArrayList;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        mNeedSwipeBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_group_members_activity);

        init();
    }

    @Override
    public void onPause() {

        UtilityBase.closeSoftInput(this);
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {

        if(!closeSearchLayout()){
            finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
        }
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
    }

    /**
     * 初始化方法
     */
    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("选择回复的人");
        topbar.setonTopbarNewLeftLayoutListener(this);

        Bundle bundle = getIntent().getExtras();
        if(bundle != null && bundle.size() > 0){
            mGroupID = bundle.getString("GroupID");
        }

        //实例化汉字转拼音类
        mCharacterParser = CharacterParser.getInstance();
        mPinyinComparatorUtil = new PinyinComparatorUtil();

        mSideBarUtil = (SideBarUtil) findViewById(R.id.sidebar);
        mCenterTip = (TextView) findViewById(R.id.centerTip);
        mSideBarUtil.setTextView(mCenterTip);

        //设置右侧触摸监听
        mSideBarUtil.setOnTouchingLetterChangedListener(new SideBarUtil.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mDataListView.setSelection(position);
                }
            }
        });

        mDataListView = (ListView) findViewById(R.id.allDataListView);
        mDataListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                BeanLectureChatUser item = mDataArrayList.get(position);
                Intent intent = new Intent(GroupMembersActivity.this, ChatMainActivity.class);
                intent.putExtra("BeanLectureChatUser", item);
                setResult(Activity.RESULT_OK, intent);
                finish(true);
            }
        });

        mDataListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 触摸按下时的操作

                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 触摸移动时的操作
                        UtilityBase.closeSoftInput(GroupMembersActivity.this);
                        break;
                    case MotionEvent.ACTION_UP:
                        // 触摸抬起时的操作

                        break;
                }
                return false;
            }
        });

        mSearchDataListView = (ListView) findViewById(R.id.searchDataListView);
        mSearchDataListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                BeanLectureChatUser item = mSearchDataArrayList.get(position);
                Intent intent = new Intent(GroupMembersActivity.this, ChatMainActivity.class);
                intent.putExtra("BeanLectureChatUser", item);
                setResult(Activity.RESULT_OK, intent);
                finish(true);
            }
        });

        mContentEditText = (EditText) findViewById(R.id.contentEditText);

        //根据输入框输入值的改变来过滤搜索
        mContentEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString().toUpperCase());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

         mAllDataLayout = (LinearLayout) findViewById(R.id.allDataLayout);
         mSearchDataLayout = (LinearLayout) findViewById(R.id.searchDataLayout);

        showProgressDialog();
        LectureUtil.getInstance().requestAllGroupInfo(GroupMembersActivity.this, mGroupID, this);
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {

        if(mSearchDataArrayList == null)
        {
            mSearchDataArrayList = new ArrayList<BeanLectureChatUser>();
        }

        mSearchDataArrayList.clear();

        if (TextUtils.isEmpty(filterStr)) {

        } else {
            for (BeanLectureChatUser bean : mDataArrayList) {
                String name = bean.NickName;
                if (name.indexOf(filterStr) != -1 || mCharacterParser.getSelling(name).toUpperCase()
                        .startsWith(filterStr)) {
                    mSearchDataArrayList.add(bean);
                }
            }
        }

        if(mSearchDataArrayList != null && mSearchDataArrayList.size() > 0){
            mSearchDataListView.setBackgroundColor(getResources().getColor(R.color.color_white));
        }else{
            mSearchDataListView.setBackgroundResource(R.drawable.mask);
        }

        // 根据a-z进行排序
        Collections.sort(mSearchDataArrayList, mPinyinComparatorUtil);

        if(mFilterAdapter == null){
            mFilterAdapter = new MembersSortAdapter(GroupMembersActivity.this, mSearchDataArrayList);
            mSearchDataListView.setAdapter(mFilterAdapter);
        }else{
            mFilterAdapter.notifyDataSetChanged();
        }
    }

    public void viewClick(View view) {
        int rid = view.getId();
        switch (rid) {
            case R.id.searchLayout:

                mSearchDataLayout.setVisibility(View.VISIBLE);
                mContentEditText.requestFocus();
                UtilityBase.openSoftInput(this);

                break;
            case R.id.cannelTextView:

                closeSearchLayout();
                break;
            default:
                break;
        }
    }

    private boolean closeSearchLayout()
    {
        boolean flag = false;
        if(mSearchDataLayout.getVisibility() == View.VISIBLE){

            if(mSearchDataArrayList != null)
            {
                mSearchDataArrayList.clear();
            }

            if(mFilterAdapter != null){
                mFilterAdapter.notifyDataSetChanged();
            }

            if(mSearchDataArrayList != null && mSearchDataArrayList.size() > 0){
                mSearchDataListView.setBackgroundColor(getColor(R.color.color_white));
            }else{
                mSearchDataListView.setBackgroundResource(R.drawable.mask);
            }

            mSearchDataLayout.setVisibility(View.GONE);
            mContentEditText.setText("");
            mContentEditText.clearFocus();
            UtilityBase.closeSoftInput(this);

            flag = true;
        }
        return flag;
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_DATA_SUCCESS:
                    hideProgressDialog();

                    ArrayList<BeanLectureChatUser> dataList = (ArrayList<BeanLectureChatUser>) msg.obj;
                    if (dataList != null && dataList.size() > 0) {
                        mDataArrayList = dataList;
                    } else {
                        if (mDataArrayList != null && mDataArrayList.size() > 0) {
                            mDataArrayList.clear();
                        }
                    }

                    if (mDataArrayList == null) {
                        mDataArrayList = new ArrayList<BeanLectureChatUser>();
                    }

                    // 根据a-z进行排序源数据
                    Collections.sort(mDataArrayList, mPinyinComparatorUtil);
                    mAdapter = new MembersSortAdapter(GroupMembersActivity.this, mDataArrayList);
                    mDataListView.setAdapter(mAdapter);

                    break;

                case MSG_DATA_FAIL:
                    hideProgressDialog();
                    break;
                default:
                    break;

            }
        }

        ;
    };

    @Override
    public void RequestComplete(Object object, Object data) {

        if (object.equals(LectureUtil.REQUEST_ALL_GROUP_INFO)) {
            // 解析json data
            ArrayList<BeanLectureChatUser> mDataArrayList = BeanLectureChatUser
                    .parseListInfo((String) data);

            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_SUCCESS;
            msg.obj = mDataArrayList;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void RequestError(Object object, int i, String data) {

        if (object.equals(LectureUtil.REQUEST_ALL_GROUP_INFO)) {
            mHandler.sendEmptyMessage(MSG_DATA_FAIL);
        }
    }
}